package com.tuiyun.jxgl.action;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.springframework.transaction.annotation.Transactional;

import com.tuiyun.jxgl.bean.Driver;
import com.tuiyun.jxgl.bean.Student;
import com.tuiyun.util.PWDUtil;

public class LoginAction {

	private String username;
	private String password;
	private Student student;
	private Driver driver;
	private String rememberMe;
	@Transactional
	public String execute() {
		Subject currentUser = SecurityUtils.getSubject();	
		//check if cookie exists
		String hashedPasswordBase64 = "";
		String cName = getCookie("uid");
		String cToken = getCookie("token");
		
		//如果用户没有输入username pwd那么使用cookie
		if (getPassword() == null && getUsername() == null){
			if(cName != null && cToken != null){			
				hashedPasswordBase64 = cToken;
				setUsername(cName);
			}else{
				//既没有username pwd 也没有 cookie 这里用currentUser
				if (currentUser.isAuthenticated()) {
					if(username == null){
						Object o = currentUser.getPrincipal();
						if (o instanceof Student) {
							student = (Student) currentUser.getPrincipal();
							
							if (student.getName().equalsIgnoreCase("admin")) {
								return "admin";
							}
							return "student";				
						} else {
							setDriver((Driver) currentUser.getPrincipal());
							return "driver";
						}
					}
				}					
			}
		}else{
			//用户输入了username pwd 则使用新的输入
			hashedPasswordBase64 = PWDUtil.encryptPWD(getPassword());
		}
		
		
//		if(cName != null && cToken != null && cName.equals(username)){			
//			hashedPasswordBase64 = cToken;
//			setUsername(cName);
//		}else if (getPassword() == null || getUsername() == null) {
//			//regular login
//			return "error";
//		}else{
//			hashedPasswordBase64 = PWDUtil.encryptPWD(getPassword());
//		}	
		
		UsernamePasswordToken token = new UsernamePasswordToken(getUsername(),
				hashedPasswordBase64);		
		try {
			currentUser.login(token);
			Object o = currentUser.getPrincipal();
			if (o instanceof Student) {
				student = (Student) o;
				if(rememberMe != null && rememberMe.equalsIgnoreCase("true")){
					//should add cookie
					addCookie("uid",student.getName());
					addCookie("token",student.getPwd());
				}
				if (student.getName().equalsIgnoreCase("admin")) {
					return "admin";
				}
				return "student";
			} else {
				driver = (Driver)o;
				if(rememberMe != null && rememberMe.equalsIgnoreCase("true")){
					//should add cookie
					addCookie("uid",driver.getName());
					addCookie("token",driver.getPwd());
				}
				driver = (Driver) o;
				return "driver";
			}

		} catch (UnknownAccountException uae) {
			System.out.println("There is no user with username of "
					+ token.getPrincipal());
		} catch (IncorrectCredentialsException ice) {
			System.out.println("Password for account " + token.getPrincipal()
					+ " was incorrect!");
		} catch (LockedAccountException lae) {
			System.out.println("The account for username "
					+ token.getPrincipal() + " is locked.  "
					+ "Please contact your administrator to unlock it.");
		}
		return "error";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

	public Driver getDriver() {
		return driver;
	}

	public void setDriver(Driver driver) {
		this.driver = driver;
	}

	public String getRememberMe() {
		return rememberMe;
	}

	public void setRememberMe(String rememberMe) {
		this.rememberMe = rememberMe;
	}

	public void addCookie(String name, String value) {		
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		cookie.setMaxAge(60 * 60 * 24 * 365);
		ServletActionContext.getResponse().addCookie(cookie);
	}

	public String getCookie(String name) {
		Cookie[] cs = ServletActionContext.getRequest().getCookies();
		for(Cookie c:cs){
			if(c.getName().equalsIgnoreCase(name))
				return c.getValue();
		}
		return null;
	}

}
